package DataProcess;


import Application.*;
import InputPkg.DataInput;
import InputPkg.DataType;
import InputPkg.PatternInput;
import InputPkg.CharInput;
import InputPkg.IntegerInput;

public class ProcessStream implements Runnable {
	App app;
	DataInput[] dataInList;
	//int procType;
	
	public ProcessStream(App a,DataInput ...dataIn){
		dataInList = dataIn;
		//procType = t;
		app = a;
	}
	/*public void match(SendMessage sendMsg,PatternInput pattern,DataInput ...dataStream){
		int num = pattern.analysis();
		if(num==1){
			
			matchChar(dataStream,pattern);
		}
	}*/
	
	
	public void matchChar(DataInput dataStream, PatternInput pattern){
		/*Pattern patReg = Pattern.compile( pattern.getPattern());
		String str = dataStream.toString();
		Matcher matcher = patReg.matcher(str);
		if(matcher.find()){
			return matcher.start();
		}
		return -1;*/
		//RegExp patReg = new RegExp(pattern.getPattern());
		AutomatonEx automaton = new AutomatonEx(pattern.getPattern());
		while(true){
			DataType tmp = dataStream.getSingleData();
			if(automaton.onlineMatch(tmp.ch)){
				app.NotifyApp("char match");
			}
		}
	}
	
	public int matchIntegerMax(PatternInput pattern,DataInput... dataStream){
		int max;
		DataInput[] dataStreamArray;
		int index = 0;
		dataStreamArray = new DataInput[dataStream.length]; 
		for(DataInput item : dataStream){
			dataStreamArray[index] = item;
			index++;
		}
		DataType tmp = dataStreamArray[0].getSingleData();
		max=tmp.i;
		for(int i=0;i<index;i++){
			DataType p = dataStreamArray[i].getSingleData();
			if(max<p.i)
				max = p.i;
		}
		if(max>Integer.parseInt(pattern.getPattern())){
			app.NotifyApp("Integer max match");
			return max;			
		}
		return -1;
	}
	public double matchIntegerAvg(PatternInput pattern,DataInput... dataStream){
		double avg;
		DataInput[] dataStreamArray ;
		int index=0;
		dataStreamArray = new DataInput[dataStream.length];
		for(DataInput item : dataStream){
			dataStreamArray[index] = item;
			index++;
		}
		double sum = 0;
		for(int i = 0;i<index;i++){
			DataType tmp = dataStreamArray[i].getSingleData();
			sum += tmp.i;
		}
		avg = sum/index;
		if(avg==Double.parseDouble(pattern.getPattern())){
			app.NotifyApp("Integer avg match");
			return avg;			//call the interface of app.
			
		}
		return -1;
	}


	@Override
	public void run() {
		// TODO Auto-generated method stub
		String str="";
		if(app.getPat().analysis(str)==1){
			matchChar(dataInList[0],app.getPat());
		}
		else{
			matchIntegerMax(app.getPat(),dataInList);
		}
		
	}
	
}
